#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
using namespace std;

const int gdefaultid = -1;
const int gsize = 4096;
const string pathname = ".";
const int projid = 0x66;

#define ERR_EXIT(m) \
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
}while(0)

class Shm
{
public:
    Shm(): _shmid(gdefaultid),_size(gsize)
    {

    }

    //创建的全新的共享内存
    void Create()
    {
        key_t k = ftok(pathname.c_str(), projid);
        if(k < 0)
        {
            ERR_EXIT("ftok");
        }
        printf("key: 0x%x\n", k);
        _shmid = shmget(k, _size, IPC_CREAT | IPC_EXCL);
        if(_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _shmid);
    }

    ~Shm()
    {

    }
private:
    int _shmid;
    int _size;
};